<template>
  <el-container>
    <!-- 数据表格 -->
    <el-main>
      <el-table
          :data="chargingRecords"
          style="width: 100%"
          :loading="loading"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNumber" label="订单号" width="150" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="phoneNumber" label="电话号码" width="120" />
        <el-table-column prop="paymentMethodName" label="支付方式" width="120" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="electricityQuantity" label="电量" width="120" />
        <el-table-column prop="stationName" label="站点名称" width="150" />
        <el-table-column prop="pileName" label="充电桩名称" width="150" />
        <el-table-column prop="status" label="交易状态" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
                @click="openDetailDialog(scope.row.id)"
                type="text"
                size="small"
            >查看详情</el-button>
            <el-button
                @click="openRefundDialog(scope.row)"
                type="primary"
                size="small"
                v-if="Number(scope.row.refundStatus) === 0"
            >退款申请</el-button>
            <el-button
                @click="openProcessDialog(scope.row)"
                type="warning"
                size="small"
                v-if="Number(scope.row.refundStatus) === 1"
            >处理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handlePageSizeChange"
          layout="total, sizes, prev, pager, next"
      />
    </el-main>

    <!-- 查看详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="充电详情"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-card>
        <div style="margin-bottom: 20px;">
          <h3>充电信息</h3>
          <el-form label-width="150px">
            <el-form-item label="充电单号">
              <span>{{ selectedRecord?.orderNumber || '-' }}</span>
            </el-form-item>
            <el-form-item label="联系电话">
              <span>{{ selectedRecord?.phoneNumber || '-' }}</span>
            </el-form-item>
            <el-form-item label="充电桩编号">
              <span>{{ selectedRecord?.pileName || '-' }}</span>
            </el-form-item>
            <el-form-item label="充电电量">
              <span>{{ selectedRecord?.electricityQuantity || '-' }} kWh</span>
            </el-form-item>
            <el-form-item label="客户姓名">
              <span>{{ selectedRecord?.customerName || '-' }}</span>
            </el-form-item>
            <el-form-item label="支付方式">
              <span>{{ selectedRecord?.paymentMethodName || '-' }}</span>
            </el-form-item>
            <el-form-item label="充电站">
              <span>{{ selectedRecord?.stationName || '-' }}</span>
            </el-form-item>
            <el-form-item label="消费金额">
              <span>¥ {{ selectedRecord?.amount || '-' }}</span>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <h3>退款记录</h3>
          <el-form label-width="150px">
            <el-form-item label="退款金额">
              <span style="color: red">¥ {{ selectedRecord?.refundAmount || '-' }}</span>
            </el-form-item>
            <el-form-item label="退款原因">
              <span>{{ selectedRecord?.refundDescription || '-' }}</span>
            </el-form-item>
            <el-form-item label="退款时间">
              <span>{{ formatTime(selectedRecord?.refundTime) }}</span>
            </el-form-item>
            <el-form-item label="处理说明">
              <span>{{ selectedRecord?.processDescription || '-' }}</span>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 退款申请对话框 -->
    <el-dialog
        v-model="refundDialogVisible"
        title="退款申请"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="充电单号">
          <el-input v-model="refundForm.orderNumber" disabled />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="refundForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="退款原因">
          <el-input v-model="refundForm.refundReason" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="退款金额">
          <el-input v-model="refundForm.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefundRequest">提交</el-button>
      </div>
    </el-dialog>

    <!-- 处理退款对话框 -->
    <el-dialog
        v-model="processDialogVisible"
        title="处理退款"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="充电单号">
          <el-input v-model="processForm.orderNumber" disabled />
        </el-form-item>
        <el-form-item label="处理说明">
          <el-input
              type="textarea"
              v-model="processForm.processDescription"
              placeholder="请输入处理说明"
              rows="5"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcessRequest">提交</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const chargingRecords = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const detailDialogVisible = ref(false);
const selectedRecord = ref(null);

const refundDialogVisible = ref(false);
const refundForm = ref({
  orderNumber: '',
  customerName: '',
  refundReason: '',
  refundAmount: '',
});

const processDialogVisible = ref(false);
const processForm = ref({
  orderNumber: '',
  processDescription: '',
});

const formatTime = (time) => {
  if (!time) return '-';
  const date = new Date(time);
  return date.toLocaleString();
};

const fetchChargingRecords = async () => {
  loading.value = true;
  try {
    const response = await axios.post('/charging/chargingRecords', {
      pageNum: currentPage.value || 1,
      pageSize: pageSize.value || 10,
    });
    chargingRecords.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error('Error fetching charging records:', error);
  } finally {
    loading.value = false;
  }
};

const openDetailDialog = async (id) => {
  try {
    const response = await axios.get(`/charging/record/${id}`);
    selectedRecord.value = response.data;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('Error fetching record details:', error);
  }
};

const openRefundDialog = (row) => {
  refundForm.value = {
    orderNumber: row.orderNumber,
    customerName: row.customerName,
    refundReason: '',
    refundAmount: '',
  };
  refundDialogVisible.value = true;
};

const submitRefundRequest = async () => {
  try {
    const response = await axios.post('/charging/apply', refundForm.value);
    if (response.data.success) {
      refundDialogVisible.value = false;
      alert('退款申请提交成功！');
      fetchChargingRecords();
    } else {
      alert('提交失败：' + response.data.message);
    }
  } catch (error) {
    console.error('提交退款申请时出错:', error);
    alert('提交失败，请稍后重试');
  }
};

const openProcessDialog = (row) => {
  processForm.value = {
    orderNumber: row.orderNumber,
    processDescription: '',
  };
  processDialogVisible.value = true;
};

const submitProcessRequest = async () => {
  try {
    const response = await axios.post('/charging/process', processForm.value);
    if (response.data.success) {
      processDialogVisible.value = false;
      alert(response.data.message || '退款处理提交成功！');
      fetchChargingRecords();
    } else {
      alert(response.data.message || '提交失败，请稍后重试');
    }
  } catch (error) {
    console.error('提交退款处理时出错:', error);
    if (error.response && error.response.data) {
      alert('提交失败：' + error.response.data.message);
    } else {
      alert('提交失败，请稍后重试');
    }
  }
};


const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchChargingRecords();
};

const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchChargingRecords();
};

onMounted(() => {
  fetchChargingRecords();
});
</script>

<style scoped>
.el-container {
  padding: 20px;
}

.el-main {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
